package org.example.blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.blog.constants.Constants;
import org.example.blog.model.Result;
import org.example.blog.model.UserInfo;
import org.example.blog.service.UserService;
import org.example.blog.utils.JwtUtils;
import org.example.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String username, String password) {
        /*
         * 1.校验参数合法性
         * 2.检查密码是否正确
         * 3.正确则返回token
         * 4.密码错误，返回错误信息
         * */
        //校验用户名密码
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        UserInfo userInfo = userService.selectByName(username);
        if (userInfo == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        //密码错误
        if (!SecurityUtils.verify(password,userInfo.getPassword())) {
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        //正确的情况返回token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME, userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        log.info("UserConroller返回结   果，token{}：", token);
        return Result.success(token);
    }

        /*
          根据用户ID
        * 获取当前登录用户信息
        * */

        @RequestMapping("/getUserInfo")
        public UserInfo getLoginUserInfo(HttpServletRequest request){
            log.info("获取用户信息....");
            //获取token
            String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
            //从token中获取登录用户ID
            Integer userId = JwtUtils.getIdByToken(token);
            if (userId==null){
                //用户未登录
                return null;
            }
            UserInfo userInfo = userService.selectById(userId);
            return userInfo;
        }

        /**
         * 根据博客ID, 获取作者信息
         * @param blogId
         * @return
         */
        @RequestMapping("/getAuthorInfo")
        public UserInfo getAuthorInfo(Integer blogId){
            if (blogId<=0){
                return null;
            }
            UserInfo userInfo = userService.getAuthorInfo(blogId);
            return userInfo;
        }


}
